import Gbx
import MySQLdb

class Panda:
    """Main class for the panda controller for trackmania forever."""
    def __init__(self):
        self.players = {}
        self.tracks ={}
        self.init_db()
        self.init_tm()
        self.sync()
        v = self.tm.GetVersion()
        print "Connected to " + v["Name"]
        self.tm.ChatSendServerMessage("Panda controller v0.1 connected")
        self.tm.set_default_method(self.cb_default)
        self.tm.add_method("TrackMania.PlayerConnect", self.cb_player_connect)
        self.tm.add_method("TrackMania.PlayerDisconnect", self.cb_player_disconnect)
        self.tm.add_method("TrackMania.PlayerChat", self.cb_player_chat)

    def init_db(self):
        self.db = MySQLdb.connect(host="localhost", user="root", passwd="Philip6", db="panda")
        self.c = self.db.cursor()

    def init_tm(self):
        self.tm = Gbx.Client('localhost:5001')
        self.tm.init()
        self.tm.Authenticate('SuperAdmin', 'SuperAdmin')
        self.tm.EnableCallbacks(True)
        

    def sync(self):
        players = self.tm.GetPlayerList(1000, 0, 1)
        for player in players:
            Player(player, self)

        tracks = self.tm.GetChallengeList(5000, 0)
        for track in tracks:
            Track(track, self)

    def cb_player_connect(self, login, isspec):
        player = self.tm.GetPlayerInfo(login)
        self.tm.ChatSendServerMessage("Connection: %s" % player["NickName"])
        Player(player, self)

    def cb_player_disconnect(self, login):
        self.tm.ChatSendServerMessage("Disconnect: %s" % self.players[login].nick)
        del self.players[login]

    def cb_default(self, *args):
        print args

    def cb_player_chat(self, uid, login, text, reg):
        if login == "pholias":
            str = build_manialink("Panda", [1.2], [])
            print str
            panda.tm.SendDisplayManialinkPageToLogin(login, str, 0, True)
        if (reg):
            self.tm.ChatSendServerMessage("Command " + login + " " + text)
            if (text == "/players"):
                print "Players:"
                for login in self.players:
                    print "%d: %s" % (self.players[login].id, self.players[login].nick)
            if (text == "/list"):
                print "Tracks:"
                for uid in self.tracks:
                    print "%s" % self.tracks[uid].name

class Track:
    def __init__(self, track, server):
        self.name = track["Name"]
        self.uid = track["UId"]
        self.file = track["FileName"]
        server.tracks[self.uid] = self

class Player:
    """Representing a connected player to the server."""
    def __init__(self, player, server):
        self.login = player["Login"]
        self.nick = player["NickName"]
        self.id = player["PlayerId"]
        server.players[self.login] = self

def build_manialink(title, widths, data):
    xml = """<?xml version='1.0' encoding='utf-8'?>
    <manialink posx='%f' posy='0.5' id='0'>
    <background bgcolor='0006'/>
    <format textsize='3' textcolor='FFFF'/>""" % (widths[0]/2.0)

    xml += "<line><cell bgcolor='0009' width='%f'><text halign='center'>$w%s</text></cell></line>" % (widths[0], title)

    xml += "</manialink>"

    return xml

panda = Panda()
while 1:
    panda.tm.tick(3600)
    
